#include "mytcpserver.h"
#include "qcoreapplication.h"
#include <algorithm>
MyTcpServer::MyTcpServer()
{

}

void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{
    qDebug()<<__FILE__<<__LINE__<<"新连接";
    TcpUserConnect *NewUser=new TcpUserConnect();
    NewUser->setSocketDescriptor(socketDescriptor);
    connect(NewUser, &TcpUserConnect::ThrowDownload,
               this, &MyTcpServer::ExecuteDownLoad);

    ConnectInfo.insert(NewUser);
}

void MyTcpServer::Match_UserTcp(TcpUserConnect *Tcp,QString UserName)
{
    UserToTcpList[UserName].insert(Tcp);
    TcpToUserName[Tcp]=UserName;
}

void MyTcpServer::Delete_UserTcp(TcpUserConnect *Tcp, QString UserName)
{
    //qDebug()<<Tcp->GetUserName();
    for(auto& _Tcp:UserToTcpList[UserName]){
        TcpToUserName.remove(_Tcp);
    }
    UserToTcpList.remove(UserName);
    TcpToUserName.remove(Tcp);
}

void MyTcpServer::distroy_instance()
{
}

TcpUserConnect *MyTcpServer::FromUserNameGetTcpSocket(QString UserName)
{

    if(UserToTcpList.count(UserName)&&UserToTcpList[UserName].size()!=0){
        return *(UserToTcpList[UserName].begin());
    }
    return nullptr;
}

QString MyTcpServer::FromTcpSocketGetUserName(TcpUserConnect *UserTcp)
{
    if(TcpToUserName.count(UserTcp)){
        return TcpToUserName[UserTcp];
    }
    return "";
}

void MyTcpServer::ExecuteDownLoad(TcpUserConnect *UsrTcp, QString UsrName)
{
    ConnectInfo.erase(UsrTcp);

    Delete_UserTcp(UsrTcp,UsrName);

    disconnect(UsrTcp, nullptr, nullptr, nullptr);
    UsrTcp->close();
    UsrTcp->deleteLater();
    UsrTcp=nullptr;
}

void MyTcpServer::ConnectUserAndTcp(TcpUserConnect *UsrTcp, QString UsrName)
{
    Match_UserTcp(UsrTcp,UsrName);
}

